<template>
    <div>
        <a-upload
            name="file"
            :multiple="true"
            action="http://127.0.0.1:8000/file_upload/"
            :headers="headers"
            :customRequest="handleChange"
        >
            <a-button>
                <a-icon type="upload"/>
                Click to Upload
            </a-button>
        </a-upload>
    </div>
</template>

<script>
import SparkMD5 from 'spark-md5'

export default {
    name: "register",
    data() {
        return {
            headers: {
                authorization: 'authorization-text',
            },
        }
    },
    methods: {
        handleChange(option) {
            // 判断是否上传
            console.log(option)

            var win_num = 0
            var bytesPerPiece = 1024 * 1024 * 100; //设置每个切片大小
            var start = 0; // 切片起始位置
            var end; // 切片终止位置
            var index = 0; //当前传送切片
            var filesize = option.file.size; //文件大小
            var filename = option.file.name; //文件名

            // //计算文件切片总数
            const totalPieces = Math.ceil(filesize / bytesPerPiece);

            console.log(totalPieces)

            while (start < filesize) {
                // 设置切片结束位置
                end = start + bytesPerPiece;
                // 判断是否切到最后一个切片， 防止切出文件
                if (end > filesize) {
                    end = filesize;
                }

                var chunk = option.file.slice(start, end);// 切割文件, 得到切片
                var sliceIndex = option.file.name + index;// 设置切片名
                console.log(sliceIndex)

                var formData = new FormData();
                formData.append("file", chunk)
                formData.append('name', sliceIndex)
                formData.append('f_name', filename)
                // 上传切片
                this.$axios.post('file_upload/',formData
                ).then(resp=>{
                    win_num += 1
                    if(win_num===totalPieces){
                        this.$axios.put('file_upload/', {
                            'index': index,
                            'filename': option.file.name
                        }).then(resp=>{
                            alert('传送成功')
                        })
                    }
                }).catch(err=>{
                    console.log(err)
                });
                //将切片起始位置移动
                start = end;
                // 当前切片下标加1
                index++;
            }

        },
    }
}
</script>

<style scoped>

</style>
